<template>
    <div class="app-container">
        <div :class="['filter-container','open']">

            <!-- 筛选框需要些双份 一种是没有展开状态下的  只有主要的几个筛选框，另一种是全部的筛选框都展示 也就是展开状态下的 -->
            <!-- 没有展开状态下的筛选框 -->
            <el-form ref="filtrateForm" :inline="true" :model="filtrateForm" label-width="100px">

                <el-form-item label="合同类型:">
                    <el-select v-model="filtrateForm.contractType" placeholder="请选择">
                        <el-option v-for="item in contract_type" :key="item.value" :label="item.lable" :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="合同状态:">
                    <el-select v-model="filtrateForm.contractState" placeholder="请选择">
                        <el-option v-for="item in contract_state" :key="item.value" :label="item.lable" :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="房屋位置:">
                    <el-select v-model="filtrateForm.parkId" placeholder="园区" style="width:100px;">
                        <el-option v-for="item in park_options" :key="item.parkId" :label="item.storeyName" :value="item.id">
                        </el-option>
                    </el-select>
                    <el-select v-model="filtrateForm.buildingId" placeholder="楼栋" :disabled="building_options.length == 0"
                        style="width:100px;margin-left: 5px;">
                        <el-option v-for="item in building_options" :key="item.value" :label="item.storeyName" :value="item.id">
                        </el-option>
                    </el-select>
                    <el-select v-model="filtrateForm.unitId" placeholder="单元" :disabled="unit_options.length == 0"
                        style="width:100px;margin-left: 5px;">
                        <el-option v-for="item in unit_options" :key="item.value" :label="item.storeyName" :value="item.id">
                        </el-option>
                    </el-select>
                    <el-select v-model="filtrateForm.floorId" placeholder="楼层" :disabled="floor_options.length == 0"
                        style="width:100px;margin-left: 5px;">
                        <el-option v-for="item in floor_options" :key="item.value" :label="item.storeyName" :value="item.id">
                        </el-option>
                    </el-select>
                    <el-select v-model="filtrateForm.houseId" placeholder="房屋" :disabled="house_options.length == 0"
                        style="width:100px;margin-left: 5px;">
                        <el-option v-for="item in house_options" :key="item.value" :label="item.storeyName" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="编号/签订人:">
                    <el-input v-model.trim="filtrateForm.customInfo" placeholder="请输入" style="width:160px;" clearable />
                </el-form-item>
                <el-form-item>
                    <!-- <el-button @click="getList()">查询</el-button>
                    <el-button v-permission="['sys:config:save']" type="primary" class="filter-item" style="margin-left: 10px;"
                        @click="handleCreate()">新增</el-button> -->
                    <!-- <el-button v-permission="['sys:config:delete']" type="danger" :disabled="dataListSelections.length <= 0"
                        @click="deleteHandle()">批量删除</el-button> -->
                </el-form-item>

            </el-form>
            <div class="filter-button">
                <el-button @click="getList()">查询</el-button>
                <el-button v-permission="['sys:config:save']" type="primary" class="filter-item" style="margin-left: 10px;"
                    @click="handleCreate()">新增</el-button>
                <!-- <el-button v-permission="['sys:config:delete']" type="danger" :disabled="dataListSelections.length <= 0"
                        @click="deleteHandle()">批量删除</el-button> -->
                <el-button :loading="downloadLoading" style="margin-left: 10px;" class="filter-item" type="primary" @click="handleDownload">
                    导出
                </el-button>
            </div>
        </div>

        <div :class="['table','open']">
            <div class="table-container">
                <el-table :key="tableKey" v-loading="listLoading" row-key="menuId" height="100%" :data="list" border fit
                    highlight-current-row style="width: 100%;" @selection-change="selectionChangeHandle">

                    <!-- <el-table-column type="selection" header-align="center" align="center" width="50" /> -->

                    <el-table-column prop="parkName" header-align="center" align="center" label="合同编号" />
                    <el-table-column prop="customerName" header-align="center" align="center" label="签订人" />
                    <el-table-column prop="contractType" header-align="center" align="center" label="合同类型">
                        <template slot-scope="scope">{{ scope.row.contractType | contractTypeFilter }}</template>
                    </el-table-column>
                    <el-table-column prop="state" header-align="center" align="center" label="合同状态">
                        <template slot-scope="scope">{{ scope.row.state | contractStateFilter }}</template>
                    </el-table-column>
                    <el-table-column prop="state" header-align="center" align="center" label="房屋位置">
                        <template
                            slot-scope="scope">{{ scope.row.parkName }}-{{ scope.row.buildingName }}-{{ scope.row.unitName }}-{{ scope.row.floorName }}-{{ scope.row.houseName }}</template>
                    </el-table-column>
                    <el-table-column prop="effectDate" header-align="center" align="center" width="180" label="开始时间">
                        <template slot-scope="scope">{{ scope.row.effectDate | toData }}</template>
                    </el-table-column>
                    <el-table-column prop="validDate" header-align="center" align="center" width="180" label="结束时间">
                        <template v-if="scope.row.validDate" slot-scope="scope">{{ scope.row.validDate | toData }}
                            &nbsp;{{scope.row.validDate | getDateDifFilter}}</template>
                        <template v-else>无固定时间</template>
                    </el-table-column>
                    <el-table-column prop="chargeType" header-align="center" align="center" label="收费周期">
                        <template slot-scope="scope">{{ scope.row.chargeType | chargeCycleFilter }}</template>
                    </el-table-column>
                    <el-table-column prop="money" header-align="center" align="center" label="租/售金额(元)" />
                    <el-table-column prop="updateTime" header-align="center" align="center" label="最近编辑时间">
                        <template slot-scope="scope">{{ scope.row.updateTime }}</template>
                    </el-table-column>
                    <el-table-column prop="updateUserName" header-align="center" align="center" label="编辑人" />
                    <el-table-column header-align="center" align="center" width="150" label="操作">
                        <template slot-scope="scope">
                            <el-button v-permission="['sys:config:update']" type="text" size="small" @click="handleUpdate(scope.row)">
                                修改
                            </el-button>
                            <el-button v-if="scope.row.contractType != 2 && scope.row.validDate" v-permission="['sys:config:update']"
                                type="text" size="small" @click="renewal(scope.row)">
                                续期
                            </el-button>
                            <!-- <el-button v-permission="['sys:config:update']" type="text" size="small" @click="start_up(scope.row)">
                                启用
                            </el-button> -->
                            <el-button v-if="scope.row.state == 1 || scope.row.state == 3" v-permission="['sys:config:update']" type="text"
                                size="small" @click="start_up(scope.row)">
                                启用
                            </el-button>
                            <el-button v-if="scope.row.state == 2 " v-permission="['sys:config:update']" type="text" size="small"
                                @click="termination(scope.row)">
                                终止
                            </el-button>
                            <!-- <el-button v-permission="['sys:config:delete']" type="text" size="small" @click="deleteHandle(scope.row)">删除
                            </el-button> -->
                        </template>
                    </el-table-column>

                </el-table>
            </div>
        </div>

        <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

        <!-- //新增或者修改弹框 -->
        <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @getList="handleFilter" />
        <!-- //续期弹框 -->
        <add-or-update-renewal v-if="addOrUpdateVisibleRenewal" ref="renewal" @getList="handleFilter" />

    </div>
</template>

<script>
import { getContractList, daletePark, getOneTree, getHouseListAll, daleteContract, startContract } from '@/api/assets'// 请求数据
import { contractExportExcel } from '@/api/index'// 请求数据
import { contractType, contractState, chargeCycle } from '@/utils/enum'
import permission from '@/directive/permission/index.js' // 权限判断指令
import checkPermission from '@/utils/permission' // 权限判断函数
import { toDate, date_utils, getDateDif } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination 分页组件
import AddOrUpdate from './add-or-update' // 新增或者修改弹框
import AddOrUpdateRenewal from './add-or-update1' // 续期弹框
// var date_utils = new DateUtilsAll()
export default {
    name: 'AssetsContract',
    components: { Pagination, AddOrUpdate, AddOrUpdateRenewal },
    directives: { permission }, // 指令
    // 过滤
    filters: {
        toData (data) {
            return date_utils.formatDate(new Date(data))
        },
        getDateDifFilter (e) {
            //结束日期 - 当前日期
            let day = getDateDif(e, date_utils.now)
            return day == 0 ? '(今天到期)' : day > 0 ? `(${day}天后过期)` : '(已过期)'
        },
        contractStateFilter (e) {
            let map = contractState;
            return map[e]
        },
        chargeCycleFilter (e) {
            let map = chargeCycle
            return map[e]
        },
        contractTypeFilter (e) {
            let map = contractType
            return map[e]
        }
    },
    data () {
        return {
            //筛选准备
            park_options: [],
            building_options: [],
            unit_options: [],
            floor_options: [],
            house_options: [],
            // 筛选框的 form 表单
            filtrateForm: {
                contractType: '',
                contractState: '',
                parkId: '',
                buildingId: '',
                unitId: '',
                floorId: '',
                houseId: '',
                customInfo: ''
            },
            // 表单验证
            rules: {
            },
            dataListSelections: [], // 批量删除选中
            tableKey: 0,
            listLoading: true, // 表格加载数据时的 loading
            list: [], // 表格数据
            total: 0, // 总条数
            listQuery: { // 表格当前页 和 当前页的展示数量
                page: 1,
                limit: 20
            },
            addOrUpdateVisible: false, // 新增和修改 弹框展示隐藏
            addOrUpdateVisibleRenewal: false, // 续期 弹框展示隐藏
            downloadLoading: false
        }
    },
    computed: {
        contract_type () {
            let arr = [{ lable: '全部', value: '' }]
            for (let key in contractType) {
                arr.push({
                    lable: contractType[key],
                    value: key
                })
            }
            return arr
        },
        contract_state () {
            let arr = [{ lable: '全部', value: '' }]
            for (let key in contractState) {
                arr.push({
                    lable: contractState[key],
                    value: key
                })
            }
            return arr
        },
    },
    watch: {
        'filtrateForm.parkId': async function (newV, oldV) {
            this.unit_options = []
            this.floor_options = []
            // console.log(newV)
            let res = await this.getOneTree(this.filtrateForm.parkId)
            this.building_options = res.list
            this.filtrateForm.buildingId = ''
            // this.filtrateForm.unitId = ''
            // this.filtrateForm.floorId = ''
            // this.filtrateForm.houseId = ''

        },
        'filtrateForm.buildingId': async function (newV, oldV) {
            this.unit_options = []
            this.floor_options = []
            let res = await this.getOneTree(this.filtrateForm.buildingId)
            if (res.list[0].type == 2) this.unit_options = res.list;
            if (res.list[0].type == 3) this.floor_options = res.list;
            this.filtrateForm.unitId = ''
            this.filtrateForm.floorId = ''
        },
        'filtrateForm.unitId': async function (newV, oldV) {
            this.floor_options = []
            let res = await this.getOneTree(this.filtrateForm.unitId)
            this.floor_options = res.list;
            this.filtrateForm.floorId = ''
            // this.filtrateForm.houseId = ''
        },
        'filtrateForm.floorId': async function (newV, oldV) {
            this.house_options = []
            let res = await this.getHouseListAll(this.filtrateForm.floorId)
            this.house_options = res.list;
            this.filtrateForm.houseId = ''
        }
    },
    created () {
        this.getList()
        this.getPark_option()
    },
    mounted () {
    },
    methods: {
        //查询园区、楼栋、单元、楼层
        async getPark_option () {
            let res = await this.getOneTree(0)
            this.park_options = res.list
        },
        async getOneTree (e) {
            if (e === '') return Promise.reject(new Error('Error'));
            const params = Object.assign({
                id: e
            }, this.listQuery)
            // 请求
            const res = await getOneTree(params).catch(e => { })
            // 失败
            if (!res) { return }
            // 成功
            const { data, code, message } = res
            // console.log("--->>>>", data)
            return data
        },
        //查询房屋
        async getHouseListAll () {
            console.log(this.park_options)
            if (e === '') return Promise.reject(new Error('Error'));
            let park = this.park_options.filter(item => {
                return item.id == this.filtrateForm.parkId
            })
            const params = Object.assign({
                parkId: this.park_options.length ? park[0].parkId : '',
                buildingId: this.filtrateForm.buildingId,
                unitId: this.filtrateForm.unitId,
                floorId: e
            }, this.listQuery)
            // 请求
            const res = await getHouseListAll(params).catch(e => { })
            // 失败
            if (!res) { return }
            // 成功
            const { data, code, message } = res
            console.log("--->>>>", data)
            return data
        },
        // 获取表格数据
        async getList () {
            this.listLoading = true
            let park = this.park_options.filter(item => {
                return item.id == this.filtrateForm.parkId
            })
            // 筛选+分页
            const params = Object.assign({
                contractType: this.filtrateForm.contractType,
                contractState: this.filtrateForm.contractState,
                parkId: park.length > 0 ? park[0].parkId : '',
                buildingId: this.filtrateForm.buildingId,
                unitId: this.filtrateForm.unitId,
                floorId: this.filtrateForm.floorId,
                houseId: this.filtrateForm.houseId,
                customInfo: this.filtrateForm.customInfo
            }, this.listQuery)
            // 请求
            const res = await getContractList(params).catch(e => { })
            // 失败
            if (!res) { this.listLoading = false; return }
            // 成功
            const { data, code, message } = res
            console.log(data)
            // data.list.forEach(item => {
            //     item.detailAddress = `${item.province}/${item.city}/${item.county}`
            //     if (!item.allHouses) {
            //         item.rentedOrAll = '--'
            //         return
            //     }
            //     item.rentedOrAll = Math.round(item.allHouses / item.rentedHouses * 100) + '%'
            // })
            this.list = data.list
            this.total = data.totalCount
            this.listLoading = false
        },
        // 重新获取表格数据 页码归为1
        handleFilter () {
            this.listQuery.page = 1
            this.getList()
        },
        // 新增数据 -- 打开弹框
        handleCreate () {
            this.addOrUpdateVisible = true
            this.$nextTick(() => {
                this.$refs.addOrUpdate.init('create')
            })
        },
        // 修改数据 -- 打开弹框
        handleUpdate (row) {
            this.addOrUpdateVisible = true
            this.$nextTick(() => {
                this.$refs.addOrUpdate.init('update', row)
            })
        },
        // 合同续期 -- 打开弹框
        renewal (row) {
            this.addOrUpdateVisibleRenewal = true
            this.$nextTick(() => {
                this.$refs.renewal.init('update', row)
            })
        },
        //启用
        async start_up (e) {
            const { code } = await startContract({}, e.id)
            this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                    this.handleFilter()// 刷新数据
                }
            })
        },
        //终止
        async termination (e) {
            // console.log(e)
            // let params = {
            //     contractId: e.id
            // }
            const { code } = await daleteContract({}, e.id)
            this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                    this.handleFilter()// 刷新数据
                }
            })
        },
        // 批量删除数据 - 多选
        selectionChangeHandle (val) {
            this.dataListSelections = val
        },
        // 删除数据 批量删除的话 不用传参
        deleteHandle (data) {
            const idS = data ? [data.id] : this.dataListSelections.map(item => { return item.id })
            const nameS = data ? [data.name] : this.dataListSelections.map(item => { return item.name })
            this.$confirm(`确定对[${nameS.join('、')}]进行[删除]操作?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                // 提交删除
                const { code, message } = await daletePark({}, idS)
                // 成功
                this.$message({
                    message: '操作成功',
                    type: 'success',
                    duration: 1500,
                    onClose: () => {
                        this.handleFilter()// 刷新数据
                    }
                })
            })
        },
        //导出 后台接口
        handleDownload () {
            this.downloadLoading = true
            const url = contractExportExcel(this.listQuery)
            const link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            // link.setAttribute('download', 'xxx.xlsx');
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
            this.downloadLoading = false
        },

    }
}
</script>
<style lang="scss" scoped>
//表格布局的注释：
//$rowLength 这个变量表示了 筛选的搜索框会有多少行，由于在不同宽度显示器下 所占行数会不一定 ，所以下面使用媒体查询 做兼容
//最小兼容至 1366
@import '~@/styles/layout-table.scss';
$rowLength: 2;
@media all and (min-width: 1659px) {
    $rowLength: 1;
    @include calculation($rowLength: $rowLength);
}
@media all and (max-width: 1659px) {
    $rowLength: 2;
    @include calculation($rowLength: $rowLength);
}
</style>
